﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace zielonka.co.uk.extensions.system
{
    /*
        Description:	In .NET, there is a IndexOf and a LastIndexOf methods that return the index of the first and the last occurrence of a match in a String object. I have an extension method to get the index of the nth occurrence:
     */

    public static partial class StringExtensions
	{
        public static int NthIndexOf(this String str, String match, int occurrence)
        {
            int i = 1;
            int index = 0;

            while (i <= occurrence &&
                (index = str.IndexOf(match, index + 1)) != -1)
            {

                if (i == occurrence)
                {
                    // Occurrence match found!
                    return index;
                }
                i++;
            }

            // Match not found
            return -1;
        }		
	}
}
